//
//  STTVChildViewController.swift
//  iPhone
//
//  Created by Toj on 3/4/24.
//

import UIKit

// MARK: - 懒加载(属性), 变量, 初始化init
class STTVChildViewController: UIViewController {
    
    var tabName = ""
    
    private let viewModel = TVChildViewModel()
    
    private var cellModels: [STTVCellModel] = [] { didSet {
        collectionView.reloadData()
    } }
    
    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        // cell之间 垂直间距
        layout.minimumLineSpacing = 8
        // cell之间 水平间距
        layout.minimumInteritemSpacing = 0
        let width = CGFloat.dv_width / 2 - 10
        layout.itemSize = CGSize(width: width, height: width)
        
        let view = UICollectionView(frame: .zero, collectionViewLayout: layout)
        view.scrollsToTop = true
        view.showsVerticalScrollIndicator = false
        view.showsHorizontalScrollIndicator = false
        view.backgroundColor = .white
        view.register(cellClass: STTVCell.self)
        view.dataSource = self
        return view
    }()
    
    deinit {
        print("-->startimes: \(st_className) func: deinit")
    }
}

// MARK: - 生命周期
extension STTVChildViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupMakeAddSubviews()
        setupMakeLayoutSubviews()
        setupMakeInitialize()
    }
}

// MARK: - 代理事件
extension STTVChildViewController: UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return cellModels.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifierClass: STTVCell.self, for: indexPath)
        cell.cellModel = cellModels[indexPath.row]
        return cell
    }
}

// MARK: - 初始化设置
private extension STTVChildViewController {
    
    func setupMakeAddSubviews() {
        view.addSubview(collectionView)
    }
    
    func setupMakeLayoutSubviews() {
        collectionView.snp.makeConstraints { make in
            make.edges.equalTo(view)
        }
    }
    
    func setupMakeInitialize() {
        viewModel.tabName = tabName
        cellModels = viewModel.setupCellModels()
    }
}
